package com.jozen.smart_toilet_system.receiver;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.content.FileProvider;

import com.jozen.modelbase.netwoek.util.AppUtil;
import com.jozen.modelbase.netwoek.util.FileUtil;
import com.jozen.smart_toilet_system.BaseApplication;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * u盘检测apk文件，自动安装更新
 * 自动拷贝人脸照片
 * 思路：获取U盘的挂载路径,直接读写U盘，读取到U盘中指定APK文件后，安装APK
 */
public class ApkInstallReceiver extends BroadcastReceiver {
    private final static String U_DISK_FILE_NAME = "jozen_8001.apk";//文件名
    private String authorities = "com.jozen.stulz_single_container.fileprovider";
    private String type = "application/vnd.android.package-archive";

    private boolean isInstalling = false;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (null == intent || null == intent.getAction()) {
            return;
        }
        switch (intent.getAction()) {
            case Intent.ACTION_MEDIA_MOUNTED:
                if (isInstalling) {
                    return;
                }
                // 获取挂载路径, 读取U盘文件
                Uri uri = intent.getData();
                if (uri != null) {
                    String filePath = uri.getPath();//u盘根目录

                    File rootFile = new File(filePath);
                    if (!rootFile.exists() || !rootFile.isDirectory()) {
                        return;
                    }

                    if (null == rootFile.listFiles() || 0 == rootFile.listFiles().length) {
                        return;
                    }
                    Log.d("", "apk，检测到u盘");
                    for (File file : rootFile.listFiles()) {
                        // 文件列表，进行相应操作...
                        if (null == file) {
                            continue;
                        }
                        if (file.getName().contains("jozen_8001")) {//jozen_stulz
                            Log.d("", "apk,检测到安装包");
                            if (isUpdate(file.getName())) {
                                Log.d("", "apk,需要升级");
                                File destFile = new File(FileUtil.getExteralPath() + File.separator + U_DISK_FILE_NAME);//android 10必须使用的路径
                                if (!destFile.exists()) {
                                    try {
                                        destFile.createNewFile();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    destFile.delete();
                                    try {
                                        destFile.createNewFile();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                                writeFileToLocal(file, destFile);
//                                installApk(context, destFile);

                                //静默安装
//                                jmInstall(context, destFile.getPath());
                                jmInstall(destFile.getPath());
                            }
                        } else if (file.isDirectory() && file.getName().equals("FACE")) {
                            copyFaceImage(file);
                        }
                    }
                }
                isInstalling = false;
                break;
        }
    }

    //============================================拷贝人脸照片=======================================================================

    //已经复制过的，不再复制
    private boolean isCopy(File localFaceFile, String fileName) {
        boolean isCopy = false;
        for (File file : localFaceFile.listFiles()) {
            if (file.getName().equals(fileName)) {
                isCopy = true;
                break;
            }
        }

        return isCopy;
    }

    private void copyFaceImage(File parentFile) {
//        LogUtils.d("apk，复制人脸照片");
        String localPath = FileUtil.getRootPath() + File.separator + "FACE";
        File localFaceFile = new File(localPath);
        if (!localFaceFile.exists()) {
            //创建本地文件夹
            localFaceFile.mkdirs();
        }
        for (File faceFile : parentFile.listFiles()) {
            if (null == faceFile || faceFile.isDirectory()) {
                continue;
            }
            if (isCopy(localFaceFile, faceFile.getName())) {
                continue;
            }
            if (faceFile.getName().toLowerCase().endsWith("jpg") || faceFile.getName().toLowerCase().endsWith("png")) {
                FileInputStream input = null;
                FileOutputStream output = null;
                try {
                    input = new FileInputStream(faceFile);
                    output = new FileOutputStream(localPath + File.separator + faceFile.getName());
                    byte[] b = new byte[1024 * 500];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (null != input) {
                        try {
                            input.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (null != output) {
                        try {
                            output.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }

        }
    }


    //====================================================静默安装apk文件=============================================================

    //静默安装
    private void jmInstall(String apkFilePath) {
        Log.d("", "apk,静默安装1");
        String packageName = BaseApplication.getInstance().getApplicationContext().getPackageName();
        try {
            new ProcessBuilder()
                    .command("pm", "install", "-i", packageName, apkFilePath)
                    .start();


//            PowerManager manager = (PowerManager) MyApplication.getInstance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
//            manager.reboot("重启");.


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //静默安装
    private void jmInstall(Context context, String apkFilePath) {
        Log.d("", "apk,静默安装2");
        File apkFile = new File(apkFilePath);
        if (!apkFile.exists()) {
            return;
        }
//        PackageInfo packageInfo = context.getPackageManager().getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES);
//        if (packageInfo != null) {
//            String packageName = packageInfo.packageName;
//            int versionCode = packageInfo.versionCode;
//            String versionName = packageInfo.versionName;
//        }

        PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
        PackageInstaller.SessionParams sessionParams = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
        sessionParams.setSize(apkFile.length());

        int mSessionId = -1;
        try {
            mSessionId = packageInstaller.createSession(sessionParams);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (mSessionId != -1) {
            boolean copySuccess = onTransfesApkFile(context, mSessionId, apkFile.getPath());
            //Log.d(TAG, "copySuccess---->" + copySuccess);
            if (copySuccess) {
                execInstallAPP(context, mSessionId);
            }
        }
    }

    private boolean onTransfesApkFile(Context mContext, int mSessionId, String apkFilePath) {
        InputStream in = null;
        OutputStream out = null;
        PackageInstaller.Session session = null;
        boolean success = false;
        try {
            File apkFile = new File(apkFilePath);
            session = mContext.getPackageManager().getPackageInstaller().openSession(mSessionId);
            out = session.openWrite("base.apk", 0, apkFile.length());
            in = new FileInputStream(apkFile);
            int total = 0, c;
            byte[] buffer = new byte[1024 * 1024];
            while ((c = in.read(buffer)) != -1) {
                total += c;
                out.write(buffer, 0, c);
            }
            session.fsync(out);
            //Log.d(TAG, "streamed " + total + " bytes");
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != session) {
                session.close();
            }
            try {
                if (null != out) {
                    out.close();
                }
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return success;
    }

    /**
     * 执行安装并通知安装结果
     */
    private void execInstallAPP(Context mContext, int mSessionId) {
        PackageInstaller.Session session = null;
        try {
            session = mContext.getPackageManager().getPackageInstaller().openSession(mSessionId);
            Intent intent = new Intent(mContext, ApkInstallReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext,
                    1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            session.commit(pendingIntent.getIntentSender());
            Log.d("", "apk,安装完成" + Thread.currentThread());

//            PowerManager manager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
//            manager.reboot("重启");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != session) {
                session.close();
            }
        }
    }

    //判断版本号，确认是否要升级
    private boolean isUpdate(String fileName) {
        fileName = fileName.replace(".apk", "");
        int vcode = AppUtil.getVersionCode();
        Log.d("", "apk,当前vcode=" + vcode);
        String[] versionNames = fileName.split("_");
        if (null != versionNames && 2 < versionNames.length) {
            String apkVersionCode = versionNames[2];
            Log.d("", "apk,apkVersionCode=" + apkVersionCode);
            if (!TextUtils.isEmpty(apkVersionCode)) {
                int desVersionCode = Integer.parseInt(apkVersionCode);
                if (desVersionCode > vcode) {
                    return true;
                }
            }
        }
        return false;
    }

    //将u盘apk文件写入本地根目录
    private void writeFileToLocal(File uFile, File destFile) {
        //写入文件
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(uFile);
            outputStream = new FileOutputStream(destFile);
            int length;
            byte[] buffer = new byte[4096];
            while (-1 != (length = inputStream.read(buffer))) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 安装apk
     *
     * @param file
     */

    private void installApk(Context context, File file) {
        Log.d("", "apk，安装");
//        restart(context, 20);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        //由于没有在Activity环境下启动Activity，设置下面的标签.
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri fileUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".fileprovider", file);
            intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
            context.grantUriPermission(context.getApplicationContext().getPackageName(), fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.grantUriPermission(context.getApplicationContext().getPackageName(), fileUri, Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    //安装完成后，自动重启
    private void restart(Context context, int seconds) {
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
        PendingIntent restartIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// 6.0及以上
            mgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000 * seconds, restartIntent);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {// 4.4及以上
            mgr.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000 * seconds, restartIntent);
        }
    }

//    protected void installApk3(Context mContext, File file) {
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        // 由于没有在Activity环境下启动Activity,设置下面的标签
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        //版本在7.0以上是不能直接通过uri访问的
//        Uri apkUri;
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//临时授权
//            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
//            apkUri = FileProvider.getUriForFile(mContext, authorities, file);
//            intent.setDataAndType(apkUri, type);
//            //兼容8.0 判断有安装第三方来源的代码
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                boolean hasInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
//                if (!hasInstallPermission) {
//                    startInstallPermissionSettingActivity(mContext);
//                    return;
//                }
//            }
//        } else {
//            //执行的数据类型
//            apkUri = Uri.fromFile(file);
//            intent.setDataAndType(apkUri, type);
//        }
//        mContext.startActivity(intent);
//    }

//    /**
//     * 跳转到设置-允许安装未知来源-页面
//     */
//    @RequiresApi(api = Build.VERSION_CODES.O)
//    private void startInstallPermissionSettingActivity(Context mContext) {
//        //注意这个是8.0新API
//        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        mContext.startActivity(intent);
//    }

//    //安装apk文件
//    private void installApk2(Context context, File file) {
//        Uri uri = FileProvider.getUriForFile(context, authorities, file);
//        Intent install = new Intent(Intent.ACTION_VIEW);
//        //为这个新apk开启一个新的activity栈
//        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        //设置intent的数据类型是应用程序application
//        install.setDataAndType(uri, type);
//        context.startActivity(install);
//    }
}
